package zsf.test.websocket.util;

import java.util.Map;

import org.apache.log4j.Logger;

import com.google.common.collect.Maps;

/** 
* @ClassName: WebClientUtils 
* @Description: 消息推送工具类
*  
*/
public class WebClientUtils {

	private static Logger logger = Logger.getLogger(WebClientUtils.class);
	
	private static Map<String, MessageSystemEndpoint> connections = Maps.newHashMap();
	
	/**
	 * 建立连接
	 * @param webClient
	 * @param webSocketUser
	 */
	public static void addWebClient(MessageSystemEndpoint webClient, String webSocketUser) {
		connections.put(webSocketUser, webClient);
	}
	
	/**
	 * 删除链接
	 * @param webSocketUser
	 */
	public static void removeWebClient(String webSocketUser) {
		connections.remove(webSocketUser);
	}
	
	/**
	* @Title: sendMessage
	* @Description: 推送消息给指定用户
	* @param account 用户账号
	* @param message 推送消息
	* @return void
	* @throws
	 */
	public static void sendMessage(String webSocketUser, String message) {
		MessageSystemEndpoint webClient = connections.get(webSocketUser);
		if(webClient != null) {
			try {
				webClient.sendMessage(message);
			} catch (Exception e) {
				System.out.println("发送信息失败");
				connections.remove(webClient);
				webClient.close();
			}
		}
	}
	
	/**
	* @Title: sendToAll
	* @Description: 发送消息给所有客户端
	* @param message 推送消息
	* @return void
	* @throws
	 */
	public static void sendToAll(String message) {
		for(MessageSystemEndpoint webClient : connections.values()) {
			try {
				webClient.sendMessage(message);
			} catch (Exception e) {
				System.out.println("发送信息给"+webClient+"失败");
				connections.remove(webClient);
				webClient.close();
			}
		}
	}
}
